from urllib import request, parse

# get請求
url = 'http://httpbin.org/get'

parms = {
    'name1': 'value1',
    'name2': 'value2'
}
querystring = parse.urlencode(parms)
u = request.urlopen(url + '?' + querystring)
resp = u.read().decode('utf-8')
# print(resp)


# post请求
url1 = 'http://httpbin.org/post'
u1 = request.urlopen(url1, querystring.encode('ascii'))
resp1 = u1.read().decode('utf-8')
print(resp1)

# 带头信息
headers = {
    'User-agent': 'none/ofyourbusiness',
    'Spam': 'Eggs'
}
req = request.Request(url1, querystring.encode('ascii'), headers=headers)
u2 = request.urlopen(req)
resp2 = u.read().decode('utf-8')
print(resp2)

# 一般现在都用requests库了
import requests

resp3 = requests.head('http://www.python.org/index.html')
status = resp3.status_code
last_modified = resp3.headers['last-modified']
content_type = resp3.headers['content-type']
content_length = resp3.headers['content-length']
print({
    'last_modified': last_modified,
    'content_type': content_type,
    'content_length': content_length
})

# requests库上传
url3 = 'http://httpbin.org/post'
files = {
    'files': ('data.csv', open('data.csv', 'rb'))
}
r = requests.post(url3, files=files)
